package cn.yx.common.security.webflux.handler;

import cn.yx.common.core.enums.ResponseCodeEnum;
import cn.yx.common.core.pojo.ResponseVo;
import cn.yx.common.security.pojo.JwtUserDetails;
import cn.yx.common.security.service.JwtTokenService;
import cn.yx.common.webflux.util.WebFluxUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * <p>用户认证成功处理器.
 * 认证成功，需要为此用户生成一个token并返回给客户端</p>
 *
 * @author Wgssmart
 */
@Component
@Slf4j
public class CustomAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler {

    private final JwtTokenService jwtTokenService;

    public CustomAuthenticationSuccessHandler(JwtTokenService jwtTokenService) {
        this.jwtTokenService = jwtTokenService;
    }

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        JwtUserDetails jwtUserDetails = (JwtUserDetails) authentication.getPrincipal();
        log.info("authentication success, user id: {}, username: {}", jwtUserDetails.getId(), jwtUserDetails.getUsername());
        String token = jwtTokenService.generateToken(jwtUserDetails);
        ServerHttpResponse response = webFilterExchange.getExchange().getResponse();
        return WebFluxUtil.write(response, ResponseVo.ok(ResponseCodeEnum.OK.getMessage(), token));
    }
}